<template>
    <div class="app-container">
        <h1 style="text-align:center">发布课程</h1>
        <el-steps :active="2" align-center style="margin-bottom: 40px" process-status="wait">
            <el-step title="填写课程基本信息"></el-step>
            <el-step title="创建课程大纲"></el-step>
            <el-step title="发布课程"></el-step>
        </el-steps>
        <el-button type="text" @click="openChapterDialogr">添加章节</el-button>

        <ul class="chanpterList">
            <li v-for="chapter in chapterNestedList" :key="chapter.id">
                <p>
                    {{ chapter.title }}
                    <span class="acts">
                        <el-button type="text" @click="oppenAppVideoDialog(chapter.id)">添加课时</el-button>
                        <el-button type="text" @click="oppenEditChapterDialog(chapter.id)">编辑</el-button>
                        <el-button type="text" @click="deleteChapter(chapter.id)">删除</el-button>
                    </span>
                </p>
                <ul class="chanpterList videoList">
                    <li v-for="video in chapter.children" :key="video.id">
                        <p>
                            {{ video.title }}
                            <span class="acts">
                                <el-button type="text" @click="oppenEditVideoDialog(video.id)">编辑</el-button>
                                <el-button type="text" @click="deleteVideo(video.id)">删除</el-button>
                            </span>
                        </p>
                    </li>
                </ul>
            </li>
        </ul>
        <el-button type="default" @click="privious()">上一步</el-button>
        <el-button type="primary" @click="next()">下一步</el-button>
        <el-dialog :title="dialogChapterTitle" :visible.sync="dialogChapterVisible">
            <el-form :model="chapter" label-width="120px" :rules="chapterRules" ref="chapterRules">
                <el-form-item label="章节标题" prop="title">
                    <el-input v-model="chapter.title"></el-input>
                </el-form-item>
                <el-form-item label="章节排序" prop="sort">
                    <el-input-number v-model="chapter.sort" controls-position="right" :min="1"></el-input-number>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogChapterVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitChapter">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加/编辑课时对话框 -->
        <el-dialog :title="dialogVideoTitle" :visible.sync="dialogVideoVisible" width="30%">
            <el-form :model="video" label-width="80px" ref="videoForm" :rules="VideoRules">
                <el-form-item label="章节标题" prop="title">
                    <el-input v-model="video.title" />
                </el-form-item>
                <el-form-item label="章节排序" prop="sort">
                    <el-input-number v-model="video.sort" controls-position="right" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="是否免费" prop="title">
                    <el-radio v-model="video.isFree" :label="1">免费</el-radio>
                    <el-radio v-model="video.isFree" :label="0">付费</el-radio>
                </el-form-item>

                <el-form-item label="上传视频" class="right">
                    <el-upload class="upload-demo" :action="`${BASE_URL}/vod/upload`" :on-success="handleUpload"
                        :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed"
                        :file-list="fileList">

                        <el-button type="primary" size="mini">上传视频</el-button>
                        <el-tooltip class="item" effect="dark" placement="right">
                            <div slot="content">
                                最大支持1G, <br />
                                支持3GP、ASF、AVI、DAT、DV、FLV、F4V、 <br />
                                GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、 <br />
                                MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、 <br />
                                SWF、TS、VOB、WMV、WEBM 等视频格式上传
                            </div>
                            <i class="el-icon-question"></i>
                        </el-tooltip>
                    </el-upload>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVideoVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitVideo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import chapterApi from '@/api/chapter'
import videoApi from "@/api/video";
import vodApi from '@/api/vod';
export default {
    data() {
        return {
            BASE_URL: process.env.BASE_API,
            fileList: [],//上传文件的列表
            dialogChapterTitle: "", //课程章节对话框
            courseId: '', //课程id
            chapterNestedList: [],//课程大纲列表
            dialogChapterVisible: false, //课程章节对话框
            dialogVideoTitle: "",//课时章节对话框
            dialogVideoVisible: false,  //课时章节对话框
            video: {
                courseId: "",
                chapterId: "",
                title: "",
                videoSourceId: "",
                videoOriginalName: "",
                sort: 0,
                isFree: "",
            },
            chapter: {
                courseId: '',
                title: '',
                sort: 1
            },
            // 格式验证
            chapterRules: {
                title: [
                    { required: true, message: '请输入章节标题', trigger: 'blur' },
                    { max: 50, message: '长度最大为50个字符', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                    { type: "number", message: '必须为数字', trigger: 'blur' }
                ]
            },
            VideoRules: {
                //表单验证规则
                title: [
                    { required: true, message: "请输入课时标题", trigger: "blur" },
                    { max: 50, message: "长度最大50个字符", trigger: "blur" },
                ],
                sort: [
                    { type: "number", message: "排序必须是数字", trigger: "blur" },
                    { required: true, message: "请输入序号", trigger: "blur" },
                ],
            },
        }
    },
    created() {
        this.init()
    },
    methods: {
        handleRemove(file, fileList) {
            console.log(file, fileList);
            // 调用api接口删除云端视频
            vodApi.deleteVod(this.video.videoSourceId).then(res=>{
                // 清空视频信息
                this.video.videoSourceId=''
                this.video.videoOriginalName=''
                this.fileList=[]
                this.$message({
                    type:'success',
                    message:'删除成功！'
                })
            })
        },
        handleExceed(files, fileList) {
            this.$message.warning(`如果要重新上传视频，请先删除原视频`);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        // 上传成功之后回调函数
        handleUpload(response, file, fileList) {
            console.log(response);
            console.log(file);
            console.log(fileList);
            // 获取视频编号
            this.video.videoSourceId = response.data.videoSourceId
            // 获取视频的原始名称
            this.video.videoOriginalName = file.name
            console.log(this.video.videoSourceId,this.video.videoOriginalName);
        },

        // 上一步
        privious() {
            this.$router.push({ path: `/course/add/${this.courseId}` })
        },
        // 下一步
        next() {
            this.$router.push({ name: 'CourseAddPublish', params: { id: this.courseId } })
        },
        // 提交章节对话框表单数据
        submitChapter() {
            // 调用api前进行格式校验
            this.$refs["chapterRules"].validate((valid) => {
                if (valid) {
                    // 验证通过
                    // 判断是添加还是更新
                    if (this.chapter.id) {
                        // 调用更新方法
                        this.updateChapter();
                    } else {
                        // 调用添加方法
                        this.addChapter()
                    }
                } else {
                    // 格式校验失败
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 添加章节
        addChapter() {
            //为课程id赋值
            console.log(this.chapter);
            this.chapter.courseId = this.courseId
            // 调用添加课程章节api
            chapterApi.addChapter(this.chapter).then(res => {
                // 提示成功信息
                this.$message({
                    type: 'success',
                    message: '添加成功'
                })
                // 关闭对话框
                this.dialogChapterVisible = false
                // 更新列表数据
                this.init()
            })
        },
        // 打开添加章节对话框
        openChapterDialogr() {
            this.dialogChapterVisible = true
        },
        // 初始化页面
        init() {
            if (this.$route.params && this.$route.params.id) {
                // 根据课程id获取当前要更新的课程信息
                this.courseId = this.$route.params.id
                this.getChapterTree(this.courseId)
            }
        },
        // 获取课程大纲
        getChapterTree(courseId) {
            chapterApi.getTreeList(courseId).then(res => {
                this.chapterNestedList = res.data
            })
        },
        //打开章节对话框
        oppenAddChapterdialog() {
            this.dialogChapterTitle = "添加章节";
            this.dialogChapterVisible = true;
            //初始化章节表单信息
            this.chapter = {
                id: "",
                title: "",
                sort: 0,
            };
        },
        //提交课时对话框表单数据
        submitVideo() {
            this.$refs["videoForm"].validate((valid) => {
                //进行数据的合法性校验
                if (valid) {
                    //验证通过
                    //判断执行的是添加还是更 新
                    if (this.video.id) {
                        //调用更新课时方法
                        // console.log("编辑");
                        // this.updateTeacher();
                        this.updateVideo()
                    } else {
                        //调用添加课时方法
                        this.addVideo();
                    }
                } else {
                    //格式校验失败
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        //添加课时
        addVideo() {
            //为课程id赋值
            this.video.courseId = this.courseId;
            // console.log(this.video);
            //调用添加课时的API
            videoApi.addVideo(this.video).then((res) => {
                //提示成功
                this.$message({
                    type: "success",
                    message: "添加成功!",
                });
                //关闭对话框
                this.dialogVideoVisible = false;
                //更新列表
                this.init();
            });
        },
        //打开编辑课程章节对话框
        oppenEditChapterDialog(chapterId) {
            this.dialogChapterTitle = "编辑章节";
            //根据章节Id获取章节信息
            chapterApi.getChapter(chapterId).then((res) => {
                this.chapter = res.data;

                //打开章节对话框
                this.dialogChapterVisible = true;
            });
        },
        oppenEditVideoDialog(videoId) {
            this.dialogVideoTitle = "编辑课时";
            this.fileList=[]
            //根据章节Id获取章节信息
            videoApi.getVideoById(videoId).then(res => {
                this.video = res.data
                if (this.video.videoOriginalName) {
                    // 为上传视频列表对象赋值
                    this.fileList = [{ name: this.video.videoOriginalName }]
                }
            })
            //打开章节对话框
            this.dialogVideoVisible = true;
        },
        //更新课程章节
        updateChapter() {
            //调用更新课程章节的App
            chapterApi.updateChapter(this.chapter).then((res) => {
                //提示成功
                this.$message({
                    type: "success",
                    message: "添加成功!",
                });
                //关闭对话框
                this.dialogChapterVisible = false;
                //更新列表
                this.init();
            });
        },
        updateVideo() {
            //调用更新课时章节的App
            videoApi.updateVideo(this.video).then((res) => {
                //提示成功
                this.$message({
                    type: "success",
                    message: "添加成功!",
                });
                //关闭对话框
                this.dialogVideoVisible = false;
                // 重置视频上传列表
                this.fileList = []
                //更新列表
                this.init();
            });
        },
        //删除课程小节
        deleteChapter(chapterId) {
            //先弹出对话框询问是否删除

            // console.log(id);
            this.$confirm("你确定要删除该章节吗", "温馨提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    //调用删除章节的api
                    chapterApi.deleteById(chapterId).then((res) => {
                        //删除成功，提示信息
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                        // 重新加载数据
                        this.init();
                    });
                })
                .catch(() => { });
        },
        //删除课时小节
        deleteVideo(videoId) {
            this.$confirm("你确定要删除该课时吗", "温馨提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    //调用删除章节的api
                    videoApi.deleteById(videoId).then((res) => {
                        //删除成功，提示信息
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                        // 重新加载数据
                        this.init();
                    });
                })
                .catch(() => { });
        },
        oppenAppVideoDialog(chapterId) {
            this.dialogVideoTitle = "添加课时";
            this.dialogVideoVisible = true;
            this.fileList = []
            //为课时的章节id赋值
            // this.video.chapterId = chapterId;

            //表单数据
            this.video = {
                id: "",
                courseId: "",
                chapterId: chapterId,
                title: "",
                videoSourceId: "",
                videoOriginalName: "",
                sort: 0,
                isFree: "",
            }
        },
    }
}
</script>
<style scoped>
.chanpterList {
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
}

.chanpterList li {
    position: relative;
}

.chanpterList p {
    float: left;
    font-size: 20px;
    margin: 10px 0;
    padding: 10px;
    height: 70px;
    line-height: 50px;
    width: 100%;
    border: 1px solid #ddd;
}

.chanpterList .acts {
    float: right;
    font-size: 14px;
}

.videoList {
    padding-left: 50px;
}

.videoList p {
    float: left;
    font-size: 14px;
    margin: 10px 0;
    padding: 10px;
    height: 50px;
    line-height: 30px;
    width: 100%;
    border: 1px dotted #ddd;
}
</style>
